package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class TrackStatReceiver {


    @Autowired
    private TrackInfoService trackInfoService;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK,durable = "true"),
            key = MqConst.ROUTING_ALBUM_STAT_UPDATE,
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE)
    ))
    public void updateTrackStat( String object,Channel channel, Message message){


        try {
            TrackStatMqVo trackStatMqVo = JSON.parseObject(object.toString(), TrackStatMqVo.class);
            if (trackStatMqVo != null) {
                trackInfoService.updateTrackStat(trackStatMqVo);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }

        } catch (Exception e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }
}
